import React, { useState } from 'react';
import { Form, Input, Modal, Select,TreeSelect ,Space,Button} from 'antd';
const { Option } = Select;

import { PlusOutlined,MinusCircleOutlined, } from '@ant-design/icons';

import styles from '../index.less';

const FormItem = Form.Item;

let configItem=["commandPort","dataBits","baudRate","stopBits","parity","ipport"];
export interface CreateFormProps {

  modalVisible: boolean;
  onSubmit: (values: any,resetForm: any) => void;
  onCancel: () => void;
  devicetype:API.DeviceTypeItem[];
  protocoltype:API.DictItem[];
  driverList?:API.DriverItem;
  arealist:API.TreeNodeItem[];
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

const CreateForm: React.FC<CreateFormProps> = (props) => {
  const [formVals] = useState<API.DeviceItem>({
    deviceTypeId:undefined,
    sights:[],
    protocolConfig:''
  });
  const [form] = Form.useForm();

  const [configRow,setConfigRow]= useState<number>(6);

  
  const { modalVisible, onSubmit: handleAdd, onCancel,devicetype,arealist,protocoltype,driverList} = props;
 

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    var devicetype=fieldsValue.deviceTypeId;
    fieldsValue.deviceTypeId=devicetype.value;
    fieldsValue.devicename=devicetype.label;
    let configs = new Map();
    if (fieldsValue.sights) {
      fieldsValue.sights.map((item) => {
        if(configItem.indexOf(item.key)==-1)
          configs.set(item.key,item.value);
      })
      let config= JSON.stringify([...configs]);
      config=config.replaceAll("[[","{").replaceAll("]]","}").replaceAll("\",\"","\":\"").replaceAll("],[",",");
      fieldsValue.protocolConfig = config;
    }
    handleAdd(fieldsValue,resetForm);
  };

  const resetForm= async () => {
    form.resetFields();
  };




  const getOption = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.dictCode} value={item.dictCode}>
        {item.dictValue}
      </Option>
    ))
  }
 
 
  const changeDriver = (e,e1) =>{
  
    var sights=[];
    var driver= driverList[e1.key];
    if(driver.driverType==1){
      sights.push({value: driver.commandPort, key: 'commandPort'});
      sights.push({value: driver.dataBits, key: 'dataBits'});
      sights.push({value: driver.baudRate, key: 'baudRate'});
      sights.push({value: driver.stopBits, key: 'stopBits'});
      sights.push({value: driver.stopBits, key: 'parity'});
      sights.push({value: '', key: 'slaveId'});
      setConfigRow(6);
    }else{
      sights.push({value: driver.ipport, key: 'ipport'});
      setConfigRow(1);
    }
      form.setFieldsValue({sights}   );
      form.setFieldsValue({'protocolType':driver.name}   );
  }
  





  return (
    <Modal
      width={800}
      destroyOnClose
      title="批量更新设备"
      visible={modalVisible}
      className={styles.deviceform}
      onOk={okHandle}
      maskClosable={false}
      onCancel={() => onCancel()}
    >

  
      <Form
        {...formLayout}
        form={form}
        initialValues={formVals}
      >   
      
      
         <FormItem
            label="设备类型"
            name="deviceTypeId"
            rules={[{ required: true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择" labelInValue={true} >
            {devicetype.map((item) => (
              <Option key={item.typeId} value={item.typeId}>
                {item.typeName}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
          label="设备品牌"
          name="deviceBrand"
          rules={[{ max:50 ,min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备型号"
          name="deviceModel"
          rules={[{   max:50 ,min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
            label="所在区域"
            name="areaId"
            rules={[{ required: true, message: '请选择所在区域' }]}
          >
             <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={arealist}
            
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
          </FormItem>
          <FormItem
            label="设备驱动"
            name="driverId"
            rules={[{ required: true, message: '请选择设备驱动' }]}
          >
            <Select placeholder="请选择设备驱动"  onChange={(e,e1)=>changeDriver(e,e1)}>
            {driverList.map((item,index) => (
              <Option key={index} value={item.id}>
                {item.name}
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="通讯协议类别"
            name="protocolType"
            rules={[{ required: true, message: '请选择通讯协议类别' }]}
          >
            <Select placeholder="请选择通讯协议类别" >
            {getOption(protocoltype)} 
            </Select>
          </FormItem>
         
         
            <div style={{margin:'0 0 24px 158px'}}>  
            <Form.List name="sights">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => (
                  <Space key={field.key} align="baseline">
                  
                    
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'key']}
                      fieldKey={[field.fieldKey, 'key']}
                      rules={[{ required: true, message: '请输入配置名' }]}
                    >
                     { field.fieldKey< configRow&& field.fieldKey<5? <Input placeholder="请输入配置名" disabled  />:  <Input placeholder="请输入配置名" />} 
                    </Form.Item>
                    {field.name ==5&& configRow==6? <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'value']}
                      fieldKey={[field.fieldKey, 'value']}
                      rules={[{ required: true, message: '请输入配置值' }]}
                    >
                         <Input   placeholder="请输入配置值"/>
                    </Form.Item>:  
                      <Form.Item
                        {...field}
                        {...formItemLayout}
                        style={{width:'220px'}}
                        name={[field.name, 'value']}
                        fieldKey={[field.fieldKey, 'value']}
                        rules={[{ required: true, message: '请输入配置值' }]}
                        
                      >
                         { field.fieldKey< configRow? <Input placeholder="请输入配置值" disabled  />:  <Input placeholder="请输入配置值" />}  
                      </Form.Item> }   
                    {field.fieldKey>=configRow?
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    :<></>
                    }
                  
                  </Space>
                ))}
               
               
                    <Button style={{ width: '448px'}} type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加配置
                    </Button>
             
                
              </>
            )}
          </Form.List>
          </div>
      </Form>
       

    </Modal>
  );
};

export default CreateForm;
